﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DTO;
using System.Data.SqlClient;
using System.Data;

namespace DAO
{
    public class CT_HoaDonSanPhamDAO
    {
        public List<CT_HoaDonSanPhamDTO> LayChiTietHoaDonSanPhamTheoMa(int mahd)
        {
            List<CT_HoaDonSanPhamDTO> listCTHDSP = new List<CT_HoaDonSanPhamDTO>();
            SqlConnection conn = null;
            SqlDataReader reader = null;
            try
            {
                String sql = "Select ct.MaNVL, SoLuong, Ten, DonViTinh  from CTHoaDonSanPham ct, NguyenVatLieu_SanPhamGiaiKhat sp Where MaHDSP = " + mahd + " and ct.MaNVL = sp.MaNVL";

                conn = DataProvider.ConnectDB();
                SqlCommand cm = new SqlCommand(sql, conn);
                reader = cm.ExecuteReader();
                while (reader.Read())
                {
                    CT_HoaDonSanPhamDTO hdspDTO = new CT_HoaDonSanPhamDTO();
                  
                    hdspDTO.MaNVL = reader.GetInt32(0);
                    hdspDTO.SoLuong = reader.GetInt32(1);
                    hdspDTO._TenNVL = reader.GetString(2);
                    hdspDTO.DonViTinh = reader.GetString(3);

                    listCTHDSP.Add(hdspDTO);
                }
            }
            catch (Exception ex)
            { String e = ex.ToString(); }
            finally
            { conn.Close(); }
            return listCTHDSP;
        }

        public String ThemChiTietHoaDonSanPham(CT_HoaDonSanPhamDTO cthdspDTO)
        {
            String mess = "";
            SqlConnection conn = null;
            try
            {
                conn = DataProvider.ConnectDB();
                String sql = "INSERT INTO CTHoaDonSanPham(MaHDSP,MaNVL,SoLuong)";
                sql += "VALUES(@MaHDSP,@MaNVL,@SoLuong)";
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                SqlParameter para;
                para = cmd.Parameters.Add("@MaHDSP", SqlDbType.Int);
                para.Value = cthdspDTO.MaHDSP;
                para = cmd.Parameters.Add("@MaNVL", SqlDbType.Int);
                para.Value = cthdspDTO.MaNVL;
                para = cmd.Parameters.Add("@SoLuong", SqlDbType.Int);
                para.Value = cthdspDTO.SoLuong;

                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                mess = "Lỗi thêm chi tiết hóa đơn";
                String e = ex.ToString();
            }
            finally
            {
                conn.Close();
            }
            return mess;
        }
    }
}
